import React from 'react';
import { Button, Form, Search, Field, Table, Balloon, Checkbox, Pagination } from '@teamix/ui';
import { ButtonIcon } from '@alife/devops-ui';
import { ENUM } from 'utils/constants';
import CompareModal from './compareModal';
import './index.scss';
import debounce from 'lodash.debounce';
import track from 'utils/track';
import intl from '../../../../locale';

const prefix = 'upgrade-step1';
const FormItem = Form.Item;

export default class TbBuildResultTag extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isModalOpen: false,
    };

    this.field = new Field(this);
  }

  componentDidMount() {
    track({
      action: 'into_step2',
    });

    // 请求表格数据
    this.props.getProjects(1);
  }

  goNext = () => {
    this.props.updateData({
      curStep: 2,
      setp1Search: '',
    });
  };

  goPrev = () => {
    this.props.updateData({
      curStep: 0,
      setp1Search: '',
    });
  };

  renderVisibilityLevel = (value) => {
    return (
      <div>
        {ENUM.visibility_level_text[value]}
        {Number(value) !== 0 && (
          <Balloon.Tooltip
            type="normal"
            trigger={
              <ButtonIcon name="question-line" style={{ marginLeft: 4, display: 'inline-block' }} />
            }
            align="t"
          >
            {intl.get({
              id: 'code-assets.containers.step1.PublicInternalProjectsCannotBe',
              defaultMessage: 'Public/ Internal 项目暂不支持升级，如需升级，请调整公开性',
            })}
          </Balloon.Tooltip>
        )}
      </div>
    );
  };

  renderImportRepoName = (value, index, record) => {
    const trigger = (
      <div className="table-cell-one-line import-repo-name-col" style={{ color: '#1B86EA' }}>
        <a href={record.original_web_url} target="_blank" rel="noreferrer">
          {value}
        </a>
      </div>
    );

    return (
      <Balloon.Tooltip trigger={trigger} align="t">
        {value}
      </Balloon.Tooltip>
    );
  };

  onPageChange = (value) => {
    this.props.getProjects(value);
  };

  search = (e) => {
    if (e.keyCode === 13) {
      this.props.getProjects(1);
    }
  };

  openModal = () => {
    this.setState({
      isModalOpen: true,
    });
  };

  render() {
    const {
      allProjects,
      selectedKeys,
      isLoadingProjects,
      setp1Search,
      sync_member,
      step1Pagination,
    } = this.props;
    const { isModalOpen } = this.state;
    const { pageSize, total, currentPage } = step1Pagination;
    return (
      <div className={`${prefix}`}>
        <div className={`${prefix}-title`}>
          {intl.get({
            id: 'code-assets.containers.step1.SelectTheProjectToBe',
            defaultMessage: '选择需升级的项目',
          })}
        </div>
        <div className={`${prefix}-desc`}>
          {intl.get({
            id: 'code-assets.containers.step1.TheFollowingAreTheProjects',
            defaultMessage: '以下为您有权限（项目组 Owner）升级的项目,请选择升级对象。查看',
          })}
          <span className="upgrade-compare-text" onClick={this.openModal}>
            {intl.get({
              id: 'code-assets.containers.step1.UpgradeMappings',
              defaultMessage: '升级映射关系',
            })}
          </span>
        </div>
        <div className={`${prefix}-form`}>
          <Form inline field={this.field}>
            <FormItem label="">
              <Search
                trim
                placeholder={intl.get({
                  id: 'code-assets.containers.step1.SearchForProjectsProjectTeams',
                  defaultMessage: '搜索项目/项目组',
                })}
                value={setp1Search}
                onChange={(value) => {
                  this.props.updateData({
                    setp1Search: value,
                  });

                  debounce(this.props.getProjects, 500)(1, value);
                }}
                onKeyDown={this.search}
              />
            </FormItem>
          </Form>
        </div>
        <div className={`${prefix}-table ${selectedKeys.length ? 'selected' : ''}`}>
          <Table
            primaryKey="original_project_id"
            dataSource={allProjects}
            loading={isLoadingProjects}
            rowSelection={{
              selectedRowKeys: selectedKeys,
              onChange: (keys) => {
                this.props.updateData({
                  selectedKeys: keys,
                });
              },
              getProps: (record) => {
                // 禁止勾选
                return {
                  disabled: Number(record.original_visibility_level) !== 0,
                };
              },
              columnProps: () => {
                return {
                  lock: 'none',
                };
              },
              titleAddons: () => {
                if (!selectedKeys.length) {
                  return null;
                }
                return (
                  <span className={`${prefix}-table-op-container`} key="op-container">
                    <span className="total-tip">
                      {intl.get(
                        {
                          id: 'code-assets.containers.step1.SelectedkeyslengthIsSelected',
                          defaultMessage: '已选择 {selectedKeysLength} 项',
                        },
                        { selectedKeysLength: selectedKeys.length },
                      )}
                    </span>
                  </span>
                );
              },
            }}
          >
            <Table.Column
              title={intl.get({
                id: 'code-assets.containers.step1.Project',
                defaultMessage: '项目',
              })}
              dataIndex="original_repo_path"
              className="import-repo-name-col"
              cell={this.renderImportRepoName}
            />
            <Table.Column
              title={intl.get({
                id: 'code-assets.containers.step1.Openness',
                defaultMessage: '公开性',
              })}
              dataIndex="original_visibility_level"
              cell={this.renderVisibilityLevel}
            />
          </Table>
        </div>
        <div className={`${prefix}-extra-info`}>
          <div className={`${prefix}-extra-info-access`}>
            <Checkbox
              checked={sync_member}
              onChange={(value) => {
                this.props.updateData({
                  sync_member: value,
                });
              }}
            >
              {intl.get({
                id: 'code-assets.containers.step1.SynchronizeProjectTeamAndProject',
                defaultMessage: '同步项目组及项目的成员',
              })}
            </Checkbox>
            <Balloon
              type="normal"
              closable={false}
              trigger={
                <ButtonIcon
                  name="question-line"
                  style={{ marginLeft: 4, display: 'inline-block' }}
                />
              }
              align="t"
            >
              {intl.get({
                id: 'code-assets.containers.step1.ThePermissionRelationshipOfThe',
                defaultMessage:
                  '同步成员在项目组/项目中的权限关系，若用户已存在，将跳过同步，不变更新平台内用户已有权限。查看',
              })}

              <span className="upgrade-compare-text" onClick={this.openModal}>
                {intl.get({
                  id: 'code-assets.containers.step1.UpgradeMappings',
                  defaultMessage: '升级映射关系',
                })}
              </span>
            </Balloon>
          </div>
          <div className={`${prefix}-extra-info-pagination`}>
            <Pagination
              onChange={this.onPageChange}
              current={currentPage}
              total={total}
              showJump={false}
              pageSize={pageSize}
              pageSizeSelector={false}
              hideOnlyOnePage
            />
          </div>
        </div>
        <div className={`${prefix}-line`} />
        <div>
          <Button type="normal" onClick={this.goPrev} style={{ marginRight: 12 }}>
            {intl.get({
              id: 'code-assets.containers.step1.PreviousStep',
              defaultMessage: '上一步',
            })}
          </Button>
          <Button type="primary" onClick={this.goNext} disabled={!selectedKeys.length}>
            {intl.get({ id: 'code-assets.containers.step1.Next', defaultMessage: '下一步' })}
          </Button>
        </div>
        {isModalOpen && (
          <CompareModal
            isModalOpen={isModalOpen}
            closeModal={() => {
              this.setState({ isModalOpen: false });
            }}
          />
        )}
      </div>
    );
  }
}
